package com.ywdnf.gomoku.util;

import com.ywdnf.gomoku.model.FrontInfoModel;
import com.ywdnf.gomoku.model.chess.Chessman;
import com.ywdnf.gomoku.model.chess.Game;
import com.ywdnf.gomoku.model.chess.Player;
import com.ywdnf.gomoku.model.chess.Round;
import com.ywdnf.gomoku.model.message.ConfirmMsgBean;
import com.ywdnf.gomoku.model.message.FrontMsgBean;
import com.ywdnf.gomoku.model.message.GmkResponse;
import com.ywdnf.gomoku.model.message.RespOptNo;
import com.ywdnf.gomoku.model.message.RightMsgBean;
import com.ywdnf.gomoku.model.message.TopMsgBean;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * gmk msg util
 *
 * @author lss
 * @date 2019-06-26, Wed
 */
public class GmkMsgUtils {

  private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd HH:mm");

  public static void sendStartGameMsg(Game game) {
    GmkResponse gmkResponse = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_RIGHT_MSG);
    Player p1 = game.getPlayer1();
    Player p2 = game.getPlayer2();
    gmkResponse.setData0(new RightMsgBean(FrontMsgBean.TYPE_SUCCESS,
        com.ywdnf.gomoku.util.StringUtils
            .splicingString(
                "当前是第 <strong><i> " + game.getCurrentRound().getSequence() + "</i></strong> 回合", "<br>",
                "玩家 1 ：", p1.getNick(), "积分：" + p1.getIntegral(), "<br>",
                "玩家 1 ：", p2.getNick(), "积分：" + p2.getIntegral(), "<br>",
                "先手玩家 ：<strong style='color: #1E90FF'>", game.getCurrentRound().getFirst().getNick(), "</strong><br>",
                "开局时间：", dtf.format(LocalDateTime.now())),
        15, true, true, "对局开始"));
    gmkResponse.setFunNo(RespOptNo.START_ROUND.getFunNo());

    gmkResponse.setData1(getFrontInfoModel(game, p1.getUserId()));
    MessageUtils.sendToUser(p1.getUserId(), ResultUtils.newSuccessfulResult(gmkResponse));

    gmkResponse.setData1(getFrontInfoModel(game, p2.getUserId()));
    MessageUtils.sendToUser(p2.getUserId(), ResultUtils.newSuccessfulResult(gmkResponse));
  }

  public static void sendPlayerMessage(Game g, Player sendPlayer, String msg) {
    sendPlayerMessage(g.getGameId(), sendPlayer.getUserId(), msg);
  }

  public static void sendPlayerMessage(String gameId, String sendPlayerId, String msg) {
    Player sendPlayer = CommonUtil.getSelfPlayer(sendPlayerId, gameId);
    GmkResponse gp = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_LEFT_MSG);
    gp.setData0(new RightMsgBean(RightMsgBean.TYPE_INFO, msg, 10, true, true, sendPlayer.getNick() + " 说："));
    gp.setFunNo(RespOptNo.PLACE_CHESS.getFunNo());
    MessageUtils
        .sendToUser(CommonUtil.getOthPlayer(sendPlayerId, gameId).getUserId(), ResultUtils.newSuccessfulResult(gp));
  }

  public static void sendPlayerConfirmMsg(String gameId, String targetUserId, ConfirmMsgBean msg) {
    GmkResponse gp = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_CONFIRM_DIALOG);
    gp.setData0(msg);
    gp.setFunNo(RespOptNo.PLACE_CHESS.getFunNo());
    MessageUtils
        .sendToUser(targetUserId, ResultUtils.newSuccessfulResult(gp));
  }

  public static void sendAIAnalysis(Game g, String sendPlayerId, String msg) {
    GmkResponse gp = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_LEFT_MSG);
    gp.setData0(new RightMsgBean(RightMsgBean.TYPE_SUCCESS, msg, 5, true, false, "AI："));
    gp.setFunNo(RespOptNo.PLACE_CHESS.getFunNo());
    MessageUtils
        .sendToUser(CommonUtil.getOthPlayer(sendPlayerId, g.getGameId()).getUserId(),
            ResultUtils.newSuccessfulResult(gp));
  }


  public static void sendCreatorPlayerIn(Game g) {
    try {
      Thread.sleep(2000);
    } catch (InterruptedException ignored) {
    }
    Player othPlayer = CommonUtil.getOthPlayer(g.getCreator().getUserId(), g);
    if (othPlayer == null) {
      return;
    }
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_TOP_MSG);
    gp2.setData0(new TopMsgBean(TopMsgBean.TYPE_SUCCESS,
        "玩家：" + othPlayer.getNick() + " 加入游戏，现在可以开始游戏", 10, true, true));
    gp2.setFunNo(RespOptNo.PLAYER_IN.getFunNo());
    // 偷偷发送创建者的ID，用来身份判断
    gp2.setData1(othPlayer);
    MessageUtils.sendToUser(g.getCreator().getUserId(), ResultUtils.newSuccessfulResult(gp2));
  }

  public static void sendPlaceChessMsg(Player p) {
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_TOP_MSG);
    gp2.setData0(new TopMsgBean(TopMsgBean.TYPE_SUCCESS, "当前到您落子", 2, true, false));
    gp2.setFunNo(RespOptNo.PLACE_CHESS.getFunNo());
    MessageUtils.sendToUser(p.getUserId(), ResultUtils.newSuccessfulResult(gp2));
  }

  public static void sendModChessMsg(Game g, Chessman c) {
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_COMMON);
    gp2.setData1(c);
    gp2.setFunNo(RespOptNo.MOD_CHESS.getFunNo());
    MessageUtils.sendToGameUserSameMsg(g, ResultUtils.newSuccessfulResult(gp2));
  }

  public static void sendRemoveChessMsg(Game g, List<Chessman> chessmenList) {
    if (chessmenList == null || chessmenList.size() == 0) {
      return;
    }
    chessmenList.forEach(c -> {
      GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_COMMON);
      gp2.setData1(c);
      gp2.setFunNo(RespOptNo.RESET_CHESS_LIST.getFunNo());
      MessageUtils.sendToGameUserSameMsg(g, ResultUtils.newSuccessfulResult(gp2));
    });
    sendPlayerMessage(g, g.getPlayer1(), "用户悔棋，请注意棋局形势变化");
    sendPlayerMessage(g, g.getPlayer2(), "用户悔棋，请注意棋局形势变化");
  }

  public static void sendPlaceChessResultMsg(Player p) {
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_TOP_MSG);
    gp2.setData0(new TopMsgBean(TopMsgBean.TYPE_SUCCESS, "落子成功，等待对方抉择", 1.2f, true, false));
    MessageUtils.sendToUser(p.getUserId(), ResultUtils.newSuccessfulResult(gp2));
  }

  public static void sendRoundResultMsg(Game game, Round round) {
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_RIGHT_MSG);
    Player p1 = game.getPlayer1();
    Player p2 = game.getPlayer2();

    gp2.setData0(new RightMsgBean(RightMsgBean.TYPE_INFO,
        StringUtils.splicingString(
            "当前回合结束", "<br>",
            "获胜玩家 ", "<strong style='color: #DDA0DD'>", round.getWinner().getNick(), "</strong><br>",
            "玩家 " + p1.getNick(),
            " 步数：" + round.getPlayerStepCount(p1) + "&emsp;&emsp;积分：" + p1.getIntegral(),
            "<br>",
            "玩家 " + p2.getNick(),
            " 步数：" + round.getPlayerStepCount(p2) + "&emsp;&emsp;积分：" + p2.getIntegral(),
            "<br>",
            "结束时间：", dtf.format(LocalDateTime.now()),
            "<br>",
            "<strong style='color: #DDA0DD'>任意一方点击开始进行下一回合</strong>"
        ), 20, true,
        true, "第 [ " + round.getSequence() + " ] 回合结束"));
    gp2.setFunNo(RespOptNo.ROUND_OVER.getFunNo());

    gp2.setData1(getFrontInfoModel(game, p1.getUserId()));
    MessageUtils.sendToUser(p1.getUserId(), ResultUtils.newSuccessfulResult(gp2));

    gp2.setData1(getFrontInfoModel(game, p2.getUserId()));
    MessageUtils.sendToUser(p2.getUserId(), ResultUtils.newSuccessfulResult(gp2));
  }

  public static void sendWinnerSurrenderMsg(Player winner) {
    GmkResponse gp2 = new GmkResponse(GmkResponse.RESPONSE_TYPE_SHOW_RIGHT_MSG);
    gp2.setData0(new RightMsgBean(RightMsgBean.TYPE_ERROR,
        "对方太菜了，竟然认输了", 10, true,
        true, "玩家投降"));
    gp2.setFunNo(RespOptNo.ROUND_OVER.getFunNo());
    MessageUtils.sendToUser(winner.getUserId(), ResultUtils.newSuccessfulResult(gp2));
  }

  private static FrontInfoModel getFrontInfoModel(Game g, String userId) {
    Player selfPlayer = CommonUtil.getSelfPlayer(userId, g);
    if (selfPlayer == null) {
      return null;
    }
    Player othPlayer = CommonUtil.getOthPlayer(userId, g);
    if (othPlayer == null) {
      return null;
    }
    return FrontInfoModel.builder()
        .meNick(selfPlayer.getNick()).meIntegral(selfPlayer.getIntegral())
        .meWinRoundCount(selfPlayer.getIntegral() / Const.WIN_AWARD_INTEGRAL)
        .othNick(othPlayer.getNick()).othIntegral(othPlayer.getIntegral())
        .othWinRoundCount(othPlayer.getIntegral() / Const.WIN_AWARD_INTEGRAL)
        .roundNo(g.getCurrentRound().getSequence())
        .creatorId(g.getCreator().getUserId())
        .winUserId(g.getCurrentRound().getWinner() != null ? g.getCurrentRound().getWinner().getUserId() : null)
        .ai(g.isAiGame())
        .build();
  }
}
